import {AsyncStorage} from 'react-native'
import {AuthModel, RoomModel} from "./model";
import {kAuthorization, kContentType} from "../constant";
import Request from "../utils/Request";
import constant from "../utils/constant";

const {Toast} = require('antd-mobile');

const STORAGE_KEY = "STORAGE_KEY_room";
export default {
    namespace: 'room',
    state: {
        list: null,
        loading: false
    },
    reducers: {
        save(state, {payload}) {
            return {...state, ...payload}
        }
    },
    effects: {


        // 保存到本地
        * saveToStorage({payload}, {call}) {
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload))
        },

        // 本地恢复
        * restoreFromStorage({payload}, {call, put, select}) {
            const data = yield call(AsyncStorage.getItem, STORAGE_KEY);
            yield put({
                type: 'save',
                payload: {...JSON.parse(data)}
            });
        },
        //清除数据
        * clear({payload}, {put, select}) {
            const room: RoomModel = yield select(state => state.auth);
            room.list = null;
            yield put({type: 'save', payload: {...room}})
        },


        //获取房间列表
        * fetchList({payload}, {put, call, select}) {
            const auth: AuthModel = yield select(state => state.auth);
            const room: RoomModel = yield select(state => state.room);
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            const result: roomListPagination = yield call(Request.get, Request.getApi().roomList, payload);
            if (result) {
                if (payload.loadmore) {
                    const content = room.list.content;
                    room.list = result;
                    room.list.content = content.concat(result.content);
                } else {
                    room.list = result;
                }
                yield put({
                    type: 'save',
                    payload: {...room}
                })
            }

        },

        //预定房间
        * reserveRoom({payload}, {call, put, select}) {
            let auth: AuthModel = yield select(state => state.auth);
            payload['params'] = {...payload};
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            payload[kContentType] = 'application/json';
            const result = yield call(Request.post, Request.getApi().roomReserve, payload);
            if (result) {
                auth.userInfo.paid = (Number(auth.userInfo.paid) - payload.paid) + '';
                yield put({
                    type: 'save',
                    payload: {...auth}
                });
                Toast.success('您已经成功提交预定请求!!', constant.ToastDuration);
            }
        },

    },
    subscriptions: {
        setup({dispatch}) {

        }
    },
};
